package common;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import org.json.JSONException;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpHelper {

    public void OkGet(final String url, final IHttpCallback httpCallback){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                try {
                    Response response = client.newCall(request).execute();
                    httpCallback.callback(response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public void OkGet(final String url, final Handler handler) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                Message message = new Message();
                Bundle bundle = new Bundle();
                try {
                    Response response = client.newCall(request).execute();
                    bundle.putString("result",response.body().string());

                } catch (IOException e) {
                   e.printStackTrace();
                   bundle.putString("error",e.getMessage());
                }finally {
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
            }
        }).start();

    }


    public String OkGet(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response =client.newCall(request).execute();
        return response.body().string();
    }
}
